<template>
  <div class="spider-status-tab">
    <!-- 搜索卡片 -->
    <div class="search-section">
      <el-card shadow="hover" class="search-card">
        <template #header>
          <div class="search-header">
            <div class="search-title">
              <el-icon><Search /></el-icon>
              <span>搜索与筛选</span>
            </div>
          </div>
        </template>

        <el-form :model="searchForm" class="search-form">
          <div class="search-form-content">
            <div class="search-form-fields">
              <el-form-item label="环境">
                <el-select
                  v-model="searchForm.env_id"
                  placeholder="选择环境"
                  clearable
                  style="width: 200px"
                >
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="env in store.envConfigsList"
                    :key="env.id"
                    :label="env.env_name"
                    :value="env.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="爬虫名称">
                <el-input
                  v-model="searchForm.spider_name"
                  placeholder="爬虫名称"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>

              <el-form-item label="存活状态">
                <el-select
                  v-model="searchForm.is_alive"
                  placeholder="选择状态"
                  clearable
                  style="width: 140px"
                >
                  <el-option label="全部" value="" />
                  <el-option label="存活" :value="1" />
                  <el-option label="死亡" :value="0" />
                </el-select>
              </el-form-item>

              <el-form-item label="搜索">
                <el-input
                  v-model="searchForm.search"
                  placeholder="爬虫名称"
                  clearable
                  style="width: 250px"
                  @keyup.enter="handleSearch"
                />
              </el-form-item>
            </div>

            <div class="search-form-actions">
              <el-button type="info" plain @click="toggleStats">
                <el-icon>
                  <component :is="showStats ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                {{ showStats ? '隐藏统计' : '显示统计' }}
              </el-button>
              <el-button type="primary" @click="handleSearch" class="search-btn">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button type="warning" @click="handleReset" class="reset-btn">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </div>
          </div>
        </el-form>
      </el-card>
    </div>

    <!-- 统计数据卡片 -->
    <div v-if="store.spiderStatusStats && Object.keys(store.spiderStatusStats).length > 0" v-show="showStats" class="stats-section">
      <el-card shadow="hover" class="stats-card">
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-label">总爬虫数</div>
            <div class="stat-value">{{ store.spiderStatusStats.total_count || 0 }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">存活</div>
            <div class="stat-value success">{{ store.spiderStatusStats.alive_count || 0 }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">死亡</div>
            <div class="stat-value warning">{{ store.spiderStatusStats.dead_count || 0 }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">平均请求队列长度</div>
            <div class="stat-value">{{ formatNumber(store.spiderStatusStats.avg_request_queue_length || 0) }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">平均失败队列长度</div>
            <div class="stat-value info">{{ formatNumber(store.spiderStatusStats.avg_failed_queue_length || 0) }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">平均失败率(%)</div>
            <div class="stat-value warning">{{ formatDecimal(store.spiderStatusStats.avg_failed_rate || 0) }}%</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 表格卡片 -->
    <div class="table-section">
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">
              <el-icon><List /></el-icon>
              <span>爬虫状态列表</span>
            </div>
            <div class="table-header-actions">
              <el-button type="success" @click="handleRefresh" class="refresh-btn" :loading="store.spiderStatusLoading" size="small">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <el-button type="info" @click="handleLoadStats" size="small">
                <el-icon><DataAnalysis /></el-icon>
                加载统计
              </el-button>
              <div class="table-info">
                <div class="pagination-control-wrapper clickable" @click="togglePagination">
                  <span class="page-count">本页 {{ store.spiderStatus.length }} 条</span>
                  <div class="divider"></div>
                  <span class="pagination-info">
                    {{ store.spiderStatusPage }}/{{ Math.ceil(store.spiderStatusTotal / store.spiderStatusPageSize) || 1 }}
                  </span>
                  <el-icon class="pagination-toggle-icon">
                    <ArrowUp v-if="paginationVisible" />
                    <ArrowDown v-else />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </template>

        <div class="table-container">
          <el-table
            :data="store.spiderStatus"
            class="enhanced-table"
            style="width: 100%"
            :height="600"
            table-layout="fixed"
            :stripe="false"
            :border="false"
            @sort-change="handleSortChange"
          >
            <el-table-column prop="id" label="ID" width="80" sortable="custom" />
            <el-table-column label="环境" min-width="120" show-overflow-tooltip>
              <template #default="{ row }">
                {{ getEnvName(row.env_id) }}
              </template>
            </el-table-column>
            <el-table-column prop="spider_name" label="爬虫名称" min-width="200" show-overflow-tooltip />
            <el-table-column prop="is_alive" label="存活状态" width="100" align="center" sortable="custom">
              <template #default="{ row }">
                <el-tag :type="row.is_alive === 1 ? 'success' : 'danger'" size="small">
                  {{ row.is_alive === 1 ? '存活' : '死亡' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="heartbeat_time" label="心跳时间" width="180" sortable="custom">
              <template #default="{ row }">
                <span v-if="row.heartbeat_time">{{ row.heartbeat_time }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="heartbeat_timeout_seconds" label="心跳超时(秒)" width="130" align="right">
              <template #default="{ row }">
                <span v-if="row.heartbeat_timeout_seconds !== null && row.heartbeat_timeout_seconds !== undefined">
                  {{ row.heartbeat_timeout_seconds }}
                </span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="request_queue_length" label="请求队列长度" width="130" align="right" sortable="custom">
              <template #default="{ row }">
                {{ formatNumber(row.request_queue_length || 0) }}
              </template>
            </el-table-column>
            <el-table-column prop="failed_queue_length" label="失败队列长度" width="130" align="right" sortable="custom">
              <template #default="{ row }">
                {{ formatNumber(row.failed_queue_length || 0) }}
              </template>
            </el-table-column>
            <el-table-column prop="failed_rate" label="失败率(%)" width="120" align="right" sortable="custom">
              <template #default="{ row }">
                <span :class="getFailedRateClass(row.failed_rate)">
                  {{ formatDecimal(row.failed_rate || 0) }}%
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="last_check_time" label="最后检查时间" width="180" sortable="custom" />
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleViewDetail(row)"
                      circle
                    >
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-tooltip>

                  <el-tooltip content="更新心跳" placement="top">
                    <el-button
                      type="success"
                      size="small"
                      @click="handleUpdateHeartbeat(row)"
                      circle
                    >
                      <el-icon><Refresh /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <transition name="pagination-slide">
          <div v-show="paginationVisible" class="pagination-section">
            <el-pagination
              v-model:current-page="store.spiderStatusPage"
              v-model:page-size="store.spiderStatusPageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="store.spiderStatusTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              background
            />
          </div>
        </transition>
      </el-card>
    </div>

    <!-- 爬虫状态详情对话框 -->
    <SpiderStatusDetailDialog
      v-model="detailDialogVisible"
      :spider-status="currentSpiderStatus"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search, Refresh, List, View, DataAnalysis,
  ArrowUp, ArrowDown
} from '@element-plus/icons-vue'
import { useRedisTaskMonitorStore } from '@/stores/redisTaskMonitor'
import SpiderStatusDetailDialog from './dialogs/SpiderStatusDetailDialog.vue'
import { createLogger } from '@/utils/logger'

const componentLogger = createLogger('SpiderStatusTab')
const store = useRedisTaskMonitorStore()

const searchForm = reactive({
  env_id: '',
  spider_name: '',
  is_alive: '',
  search: ''
})

const paginationVisible = ref(false)
const showStats = ref(false)
const detailDialogVisible = ref(false)
const currentSpiderStatus = ref(null)
const sortField = ref('last_check_time')
const sortOrder = ref('desc')

// 获取环境名称
const getEnvName = (envId) => {
  const env = store.envConfigsList.find(e => e.id === envId)
  return env ? env.env_name : `环境${envId}`
}

// 格式化数字
const formatNumber = (num) => {
  if (num === null || num === undefined) return '0'
  return num.toLocaleString()
}

// 格式化小数
const formatDecimal = (num) => {
  if (num === null || num === undefined) return '0.00'
  return parseFloat(num).toFixed(2)
}

// 获取失败率样式类
const getFailedRateClass = (failedRate) => {
  if (failedRate > 10) return 'failed-rate-high'
  if (failedRate > 5) return 'failed-rate-medium'
  return 'failed-rate-low'
}

// 搜索
const handleSearch = async () => {
  store.spiderStatusPage = 1
  await fetchData()
  await fetchStats()
}

// 重置
const handleReset = () => {
  searchForm.env_id = ''
  searchForm.spider_name = ''
  searchForm.is_alive = ''
  searchForm.search = ''
  store.spiderStatusPage = 1
  fetchData()
  fetchStats()
}

// 刷新
const handleRefresh = () => {
  fetchData()
}

// 加载统计
const handleLoadStats = async () => {
  await fetchStats()
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const data = await store.fetchSpiderStatusDetail(row.id)
    currentSpiderStatus.value = data
    detailDialogVisible.value = true
  } catch (error) {
    componentLogger.error('获取爬虫状态详情失败', error)
  }
}

// 更新心跳
const handleUpdateHeartbeat = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要更新爬虫 "${row.spider_name}" 的心跳吗？`,
      '确认更新心跳',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await store.updateSpiderHeartbeat(row.id, {
      heartbeat_time: new Date().toISOString().slice(0, 19).replace('T', ' ')
    })
    ElMessage.success('心跳更新成功')
    await fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('更新爬虫心跳失败', error)
    }
  }
}

// 排序
const handleSortChange = ({ prop, order }) => {
  if (prop) {
    sortField.value = prop
    sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
    fetchData()
  }
}

// 分页
const handleSizeChange = (size) => {
  store.spiderStatusPageSize = size
  store.spiderStatusPage = 1
  fetchData()
}

const handlePageChange = (page) => {
  store.spiderStatusPage = page
  fetchData()
}

const togglePagination = () => {
  paginationVisible.value = !paginationVisible.value
}

const toggleStats = () => {
  showStats.value = !showStats.value
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const params = {}
    
    if (searchForm.env_id) {
      params.env_id = searchForm.env_id
    }

    await store.fetchSpiderStatusStats(params)
  } catch (error) {
    componentLogger.error('获取爬虫状态统计失败', error)
  }
}

// 获取数据
const fetchData = async () => {
  try {
    const params = {
      page: store.spiderStatusPage,
      pageSize: store.spiderStatusPageSize,
      sort: sortField.value,
      order: sortOrder.value
    }

    if (searchForm.env_id) {
      params.env_id = searchForm.env_id
    }

    if (searchForm.spider_name) {
      params.spider_name = searchForm.spider_name
    }

    if (searchForm.is_alive !== '') {
      params.is_alive = searchForm.is_alive
    }

    if (searchForm.search) {
      params.search = searchForm.search
    }

    await store.fetchSpiderStatus(params)
  } catch (error) {
    componentLogger.error('获取爬虫状态列表失败', error)
  }
}

// 导出方法供父组件调用
defineExpose({
  fetchData
})

onMounted(async () => {
  // 加载环境列表
  await store.fetchEnvConfigsList()
  // 加载数据
  await fetchData()
  // 加载统计
  await fetchStats()
})
</script>

<style scoped>
.spider-status-tab {
  padding: 0;
}

.search-section {
  margin-bottom: 24px;
}

.stats-section {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 20px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.stat-value.success {
  color: #67c23a;
}

.stat-value.info {
  color: #409eff;
}

.stat-value.warning {
  color: #f56c6c;
}

.search-card,
.table-card {
  border-radius: 8px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.search-form {
  margin-top: 0;
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form-fields {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  flex: 1;
}

.search-form-actions {
  display: flex;
  gap: 10px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.table-header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.pagination-control-wrapper:hover {
  background-color: #f5f7fa;
}

.page-count {
  font-size: 12px;
  color: #606266;
}

.divider {
  width: 1px;
  height: 14px;
  background-color: #dcdfe6;
}

.pagination-info {
  font-size: 12px;
  color: #909399;
}

.pagination-toggle-icon {
  font-size: 12px;
  color: #909399;
}

.table-container {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.text-muted {
  color: #909399;
  font-style: italic;
}

.failed-rate-high {
  color: #f56c6c;
  font-weight: 600;
}

.failed-rate-medium {
  color: #e6a23c;
}

.failed-rate-low {
  color: #67c23a;
}

.pagination-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.pagination-slide-enter-active,
.pagination-slide-leave-active {
  transition: all 0.3s ease;
}

.pagination-slide-enter-from,
.pagination-slide-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
